
export default function (methods, url, parmas = {}) {
    //设置异步
    return new Promise((resolve, reject) => {

        //创建xhr请求
        const xhr = new XMLHttpRequest()
        //安装状态改变函数
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    //为什么const data = JSON.parse(xhr.response)
                    const data = JSON.parse(xhr.response)
                    resolve(data)
                } else {
                    if (xhr.status == 401) {
                        alert('未登录或登录超时');
                        location = '/login.html?url=' + encodeURIComponent(location.href)
                        alert('服务器睡着了');
                        reject(xhr.status);
                    }
                }
            }
        }
        const data = Object.entries(parmas).map(item => item[0] + '=' +
            encodeURIComponent(item[1])).join('&')
        if (methods.toLowerCase() == 'get') {
            url += '?' + data;
        }
        xhr.open(methods, url, true)
        if (methods.toLowerCase() == 'post') {
            xhr.setRequestHeader('Content-Type', 'application/json');
        }
        xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'))
        xhr.send(methods.toLowerCase() == 'post' ? JSON.stringify(parmas) : null)
    })
}






